package ws_socket

import (
	"bytes"
	"fmt"
	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
	"time"
)

type Client struct {
	user       string
	pwd        string
	ip         string
	port       string
	sshClient  *ssh.Client
	sftpClient *sftp.Client
}

func (c *Client) Config() *ssh.ClientConfig {
	return &ssh.ClientConfig{
		User: c.user,
		Auth: []ssh.AuthMethod{
			ssh.Password(c.pwd),
		},
		Timeout:         30 * time.Second,
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}

}

func (c *Client) Run(cmd string) string {
	client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", c.ip, 22), c.Config())
	if err != nil {
		panic("Failed to dial: " + err.Error())
	}
	defer client.Close()
	// 执行命令
	session, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	defer session.Close()
	var stdoutBuf bytes.Buffer
	session.Stdout = &stdoutBuf

	if err := session.Run(cmd); err != nil {
		panic("Failed to run: " + err.Error())
	}
	return stdoutBuf.String()
}
